#!python3
# -*- coding: utf-8 -*-

import json, requests, sys,time


class WeChat2tag(object):
    def __init__(self, title, description, party_id):
        self.url = "https://qyapi.weixin.qq.com"
        self.corpid = 'xxxx'
        self.secret = 'xxxx1AF-pVpyAERS8ciraIaqtTYJn0vrr0J9Q'
        self.agentid = '1000003'
        self.title = title
        self.description = description
        self.party_id = party_id

    def access_token(self):
        url_arg = '/cgi-bin/gettoken?corpid={id}&corpsecret={crt}'.format(
            id=self.corpid, crt=self.secret)
        url = self.url + url_arg
        response = requests.get(url=url)
        text = response.text
        self.token = json.loads(text)['access_token']

    def messages(self):
        values = {
            "totag": self.party_id,
            "agentid": self.agentid,
            "msgtype": "markdown",
            "markdown": {"content": self.title + "\n" + self.description}
        }

        self.msg = json.dumps(values, ensure_ascii=False).encode('utf-8')
        return self.msg

    def sendMessage(self):
        accessToken = self.token
        msg = self.messages()
        send_url = '{url}/cgi-bin/message/send?access_token={token}'.format(url=self.url, token=accessToken)
        response = requests.post(url=send_url, data=msg)
        errcode = json.loads(response.text)['errcode']
        if errcode == 0:
            print('Success')
        else:
            print('Failed')

